package uk.co.droidinactu.sony.prst1.home.view;

import uk.co.droidinactu.sony.prst1.home.R;
import uk.co.droidinactu.sony.prst1.home.data.Collection;
import uk.co.droidinactu.sony.prst1.home.data.SonyDataModel;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

public final class CollectionsActivity extends AbstractListActivity implements OnItemClickListener, OnClickListener {

    private static final int[] collctnColsMapTo = new int[] { R.id.collection_list_item_title,
            R.id.collection_list_item_count };

    private static final String[] collctnColumns = new String[] { Collection.COLUMN_NAME_TITLE,
            Collection.COLUMN_NAME_UUID };

    public static final String LOG_TAG = "CollectionsActivity";
    private static final int NUMBER_COLLECTIONS_SHOWN = 10;
    private int collectionsStart = 0;
    private Cursor cursr;
    private SonyDataModel dataModel;
    private String filterChar = null;
    private LinearLayout indexBtns;

    private ListView listView;

    private final String PREF_SORT_BY = "PREF_SORT_BY";
    private CollectionSortBy sortBy = CollectionSortBy.TITLE;
    private TextView txtSortOrdr;
    private TextView txtViewTitle;

    @Override
    public void onClick(final View v) {

        if (v.getTag() == null) {
            final String btnPressed = ((Button) v).getText().toString();
            this.filterChar = btnPressed;
            this.updateList();

        } else if (v.getTag().equals("collection_list_txt_books")) {
            this.filterChar = null;
            this.updateList();

        } else if (v.getTag().equals("next_collection_page")) {
            this.collectionsStart = this.collectionsStart + CollectionsActivity.NUMBER_COLLECTIONS_SHOWN;
            this.updateList();

        } else if (v.getTag().equals("prev_collection_page")) {
            this.collectionsStart = this.collectionsStart - CollectionsActivity.NUMBER_COLLECTIONS_SHOWN;
            if (this.collectionsStart < 0) {
                this.collectionsStart = 0;
            }
            this.updateList();

        } else if (v.getTag().equals("collection_list_btn_sort")) {
            if (this.sortBy == CollectionSortBy.TITLE) {
                this.sortBy = CollectionSortBy.NBR_BOOKS;
            } else {
                this.sortBy = CollectionSortBy.TITLE;
            }
            // this.updateList();
            this.showNotImplementedDialog();

        } else if (v.getTag().equals("collection_list_btn_search")) {
            this.showNotImplementedDialog();

        }
    }

    /** Called when the activity is first created. */
    @Override
    public void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.collection_list);
        this.listView = (ListView) this.findViewById(R.id.collection_list);
        this.listView.setOnItemClickListener(this);

        // this.btnNextPage = (Button)
        // this.findViewById(R.id.collection_list_btn_next_page);
        // this.btnNextPage.setOnClickListener(this);
        // this.btnPrevPage = (Button)
        // this.findViewById(R.id.collection_list_btn_prev_page);
        // this.btnPrevPage.setOnClickListener(this);

        this.txtViewTitle = (TextView) this.findViewById(R.id.collection_list_txt_books);
        this.txtSortOrdr = (TextView) this.findViewById(R.id.collection_list_txt_sort_order);
        this.indexBtns = (LinearLayout) this.findViewById(R.id.collection_list_btn_index);

        this.txtViewTitle.setOnClickListener(this);

        this.indexBtns.removeAllViews();
        Button btn = new Button(this);
        btn.setOnClickListener(this);
        btn.setText("0");
        this.indexBtns.addView(btn);

        for (char ch = 'A'; ch <= 'Z'; ch++) {
            btn = new Button(this);
            btn.setOnClickListener(this);
            btn.setText("" + ch);
            this.indexBtns.addView(btn);
        }

    }

    @Override
    public void onItemClick(final AdapterView<?> parent, final View view, final int position, final long id) {
        final Intent incdntDetailsIntnt = new Intent(this, BooksActivity.class);
        incdntDetailsIntnt.putExtra(BooksActivity.SELECTED_COLLECTION_ID, id);
        this.startActivity(incdntDetailsIntnt);
    }

    @Override
    protected void onPause() {
        super.onPause();
        final SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
        final SharedPreferences.Editor ed = mPrefs.edit();
        ed.putInt(this.PREF_SORT_BY, this.sortBy.ordinal());
        ed.commit();
    }

    @Override
    protected void onResume() {
        super.onResume();
        final SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
        final int tmpSortOrdr = mPrefs.getInt(this.PREF_SORT_BY, CollectionSortBy.TITLE.ordinal());
        if (tmpSortOrdr == CollectionSortBy.NBR_BOOKS.ordinal()) {
            this.sortBy = CollectionSortBy.NBR_BOOKS;
        } else {
            this.sortBy = CollectionSortBy.TITLE;
        }
        if (this.dataModel == null) {
            this.dataModel = new SonyDataModel(this);
        }
        this.updateList();
    }

    private void updateList() {
        try {
            if (this.filterChar != null && this.filterChar.length() > 0) {
                this.txtViewTitle.setText(String.format(
                        this.getResources().getString(R.string.collection_list_title_filtered), this.filterChar));
            } else {
                this.txtViewTitle.setText(this.getResources().getString(R.string.collection_list_title));
            }
            this.cursr = this.dataModel.getCollections(this.collectionsStart,
                    CollectionsActivity.NUMBER_COLLECTIONS_SHOWN, this.filterChar);

            this.startManagingCursor(this.cursr);

            final SimpleCursorAdapter tmpAdaptor = new SimpleCursorAdapter(this, R.layout.collection_list_item,
                    this.cursr, CollectionsActivity.collctnColumns, CollectionsActivity.collctnColsMapTo);

            tmpAdaptor.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
                @Override
                public boolean setViewValue(final View view, final Cursor cursor, final int columnIndex) {
                    boolean retval = false;
                    final int idColIndex = cursor.getColumnIndexOrThrow(Collection.COLUMN_NAME_UUID);
                    final int titleColIndex = cursor.getColumnIndexOrThrow(Collection.COLUMN_NAME_TITLE);

                    if (columnIndex == idColIndex) {
                        try {
                            final TextView txtbookCount = (TextView) view;
                            final String collcnName = cursor.getString(titleColIndex);
                            final Cursor crsr = CollectionsActivity.this.dataModel.getBooksInCollection(collcnName,
                                    BookSortBy.TITLE);
                            final int bookCount = crsr.getCount();
                            crsr.close();
                            txtbookCount.setText("(" + bookCount + ")");
                            retval = true;
                        } catch (final Exception e) {
                        }
                        retval = true;
                    }
                    return retval;
                }
            });
            this.listView.setAdapter(tmpAdaptor);
            tmpAdaptor.notifyDataSetChanged();
        } catch (final Exception e) {
            Log.e(LOG_TAG, "exception populating list", e);
        }
    }
}
